<?php
/**
 * Created by PhpStorm.
 * User: iwm
 * Date: 2017/1/9
 * Time: 15:50
 */


namespace app\api\model\page\user;


use app\api\model\dao\UserCoupon;
use app\library\Flag;
use think\image\Exception;

class UseCoupon
{
    /**
     * @param $user_id
     * @param $coupon_id
     * @param $coupon_status
     * @return bool|string
     * @throws \think\Exception
     */
    public function consumeCoupon($user_id, $coupon_id, $coupon_status)
    {
        $status = [
            Flag::USER_COUPON_STATUS_EXPIRED,
            Flag::USER_COUPON_STATUS_USED,
            Flag::USER_COUPON_STATUS_NOT_USED,
        ];
        if (!in_array($coupon_status, $status)) {
            return '设置优惠券状态正确';
        }
        Db::startTrans();
        try {

            $obj = new UserCoupon();
            $conds = [
                'user_id' => $user_id,
                'coupon_id' => $coupon_id,
            ];
            $data = [
                'status' => $coupon_status,
            ];
            $ret = $obj->updateCoupon($conds, $data);
            if (false === $ret) {
                throw new \think\Exception('更新优惠券状态失败');
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

}